package org.gesplan.ui;

import ca.odell.glazedlists.swing.AutoCompleteSupport;
import java.awt.EventQueue;
import java.beans.Beans;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.gesplan.controller.GenericController;
import org.gesplan.controller.WorkJpaController;
import org.gesplan.controller.WorkLocationJpaController;
import org.gesplan.entity.*;
import org.gesplan.entity.sig.*;
import org.gesplan.exceptions.NonexistentEntityException;
import org.gesplan.util.CalendarManager;
import org.gesplan.util.Utils;


/**
 *
 * @author Roger
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public class WorkAddPanel extends AbstractPanel {

    static final long MILIS_DIA = 24 * 60 * 60 * 1000;
    private WorkJpaController workController;
    private WorkLocationJpaController workLocationController;
    private String serviceId;
    private String action = "new";
    private static AutoCompleteSupport supportTask;
    private static AutoCompleteSupport supportLocation;
    private static AutoCompleteSupport support;
    private Work work;
    private boolean reset;
    private WorkAddFrame parent;


    public WorkAddPanel() {
        initComponents();
        initConfig();
    }


    private void initConfig() {

        workController = new WorkJpaController();
        workLocationController = new WorkLocationJpaController();
        if (!Beans.isDesignTime()) {
            workController.getEntityManager();
        }
        dataIniciDateChooser.setDate(new Date());

        // Set DefaultModel for JLists
        DefaultListModel model = new DefaultListModel();
        assignedStaffList.setModel(model);
        model = new DefaultListModel();
        assignedLocationList.setModel(model);

    }


    public void setAction(String action) {
        this.action = action;
    }


    public void setServiceId(String serviceId) {
        this.serviceId = serviceId;
    }


    public void setWork(Work work) {
        this.work = work;
    }


    public void setParent(WorkAddFrame parent) {
        this.parent = parent;
    }


    public void initCombos() {

        String sqlTask = bundle.getString("qryTask2");
        String sqlService = bundle.getString("qryService2");
        if (serviceId != null) {
            sqlTask += " WHERE ser.id = '" + serviceId + "'";
            sqlService += " WHERE ser.id = '" + serviceId + "'";
        }
        sqlTask += " ORDER BY t.description";
        sqlService += " ORDER BY ser.description";
        supportTask = GenericController.fillComboBox(sqlTask, taskComboBox, supportTask);

        GenericController.fillComboBox(bundle.getString("qryLocationGroup"), locationGroupComboBox, support);
        locationGroupComboBox.setSelectedIndex(-1);

        GenericController.fillComboBox(sqlService, serviceComboBox, support);
        serviceComboBox.setSelectedIndex(serviceId == null ? -1 : 0);
        serviceComboBox.setEnabled(serviceId == null);

        GenericController.fillComboBox(bundle.getString("qryStaff"), staffComboBox, support);

    }


    public void initWork() {

        try {
            // If work is defined, set values
            if (work != null) {
                staffComboBox.getEditor().setItem(work.getStaffId().getNameFull());
                addStaffToList();
                serviceComboBox.getEditor().setItem(work.getTaskId().getSubgroupId().getServiceId());
                taskComboBox.getEditor().setItem(work.getTaskId());
                dataIniciDateChooser.setDate(work.getDateWork());
                Float hours = (Float) work.getTimeElapsed();
                hoursTextField.setText(hours.toString());
                sectionComboBox.setSelectedItem(work.getSectionId());
                commentsTextArea.setText(work.getComments());
                // Load locations into List
                for (WorkLocation workLocation : work.getWorkLocationCollection()) {
                    String tableName = workLocation.getLocationGroup().getTableName();
                    String tableId = workLocation.getLocationGroup().getTableId();
                    String id = workLocation.getLocationId();
                    String jql = "SELECT loc FROM " + tableName + " loc WHERE loc." + tableId + " = '" + id + "'";
                    Query query = entityManager.createQuery(jql);
                    Object elem = query.getSingleResult();
                    DefaultListModel model = (DefaultListModel) assignedLocationList.getModel();
                    int pos = model.getSize();
                    model.add(pos, elem);
                }
            }
        } catch (Exception ex) {
            logger.severe(ex.getMessage());
        }

    }


    private void addStaffToList() {
        try {
            Staff staff = (Staff) staffComboBox.getSelectedItem();
            if (staff == null) {
                JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_STAFF"), bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
                staffComboBox.requestFocusInWindow();
                return;
            }
            DefaultListModel model = (DefaultListModel) assignedStaffList.getModel();
            int pos = model.getSize();
            model.add(pos, staff);
        } catch (ClassCastException ex) {
            logger.warning(ex.getMessage());
        }
    }


    private void removeStaffToList() {
        int pos = assignedStaffList.getSelectedIndex();
        if (pos != -1) {
            DefaultListModel model = (DefaultListModel) assignedStaffList.getModel();
            model.remove(pos);
        }
    }


    private void addLocationToList() {
        Object elem = locationComboBox.getSelectedItem();
        if (elem != null) {
            DefaultListModel model = (DefaultListModel) assignedLocationList.getModel();
            int pos = model.getSize();
            model.add(pos, elem);
        }
    }


    private void removeLocationToList() {
        int pos = assignedLocationList.getSelectedIndex();
        if (pos != -1) {
            DefaultListModel model = (DefaultListModel) assignedLocationList.getModel();
            model.remove(pos);
        }
    }


    private void saveWork() throws RuntimeException {

        // Mandatory fields
        Date initialDate = dataIniciDateChooser.getDate();
        Date finalDate = dataFiDateChooser.getDate();
        long daysElapsed = 1;
        if (dataFiDateChooser.getDate() != null) {
            daysElapsed = ((finalDate.getTime() - initialDate.getTime()) / (MILIS_DIA)) + 1;
        }
        if (daysElapsed < 0) {
            JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_DATES"), bundle.getString("VALIDATE_FORM"), JOptionPane.WARNING_MESSAGE);
            dataFiDateChooser.requestFocusInWindow();
            return;
        }

        // Get assigned staffs
        int sizeAssigned = assignedStaffList.getModel().getSize();
        if (sizeAssigned < 1) {
            JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_STAFF"), bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            staffComboBox.requestFocusInWindow();
            return;
        }

        // Get task
        Task task = (Task) taskComboBox.getSelectedItem();
        if (task == null) {
            JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_TASK"), bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            taskComboBox.requestFocusInWindow();
            return;
        }

        // Get section
        Section section = (Section) sectionComboBox.getSelectedItem();
        if (section == null) {
            JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_SECTION"), bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            sectionComboBox.requestFocusInWindow();
            return;
        }

        // Get hours
        String hours = hoursTextField.getText().replace(",", ".");
        float timeElapsed = 0;
        Float totalHours;
        try {
            totalHours = Float.parseFloat(hours);
            timeElapsed = totalHours / daysElapsed;
            if (timeElapsed < 0) {
                JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_HOURS"), bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
                hoursTextField.requestFocusInWindow();
                hoursTextField.selectAll();
                return;
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, bundle.getString("VALIDATE_HOURS1"), bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
            hoursTextField.requestFocusInWindow();
            hoursTextField.selectAll();
            return;
        }

        // Optional Fields
        String comments = commentsTextArea.getText();

        // Get assigned locations
        int sizeLocations = assignedLocationList.getModel().getSize();
        List<WorkLocation> listWl = new ArrayList<>();
        for (int i = 0; i < sizeLocations; i++) {
            Object location = assignedLocationList.getModel().getElementAt(i);
            WorkLocation wl = new WorkLocation();
            Integer id = null;
            if (location instanceof CarrererEixos) {
                CarrererEixos elem = (CarrererEixos) location;
                wl.setLocationId(elem.getCcar());
                id = 1;
            } else if (location instanceof Barris) {
                Barris elem = (Barris) location;
                wl.setLocationId(elem.getCodi());
                id = 2;
            } else if (location instanceof LlumQuadre) {
                LlumQuadre elem = (LlumQuadre) location;
                wl.setLocationId(elem.getGeoname());
                id = 3;
            } else if (location instanceof Building) {
                Building elem = (Building) location;
                wl.setLocationId(elem.getId());
                id = 4;
            } else if (location instanceof EvUgEspais) {
                EvUgEspais elem = (EvUgEspais) location;
                wl.setLocationId(elem.getCodiUg());
                id = 5;
            } else if (location instanceof Camins) {
                Camins elem = (Camins) location;
                wl.setLocationId(elem.getCodiCami());
                id = 6;
            } else if (location instanceof EspaisForestals) {
                EspaisForestals elem = (EspaisForestals) location;
                wl.setLocationId(elem.getCodiUg());
                id = 7;
            } else if (location instanceof XarxaFluvial) {
                XarxaFluvial elem = (XarxaFluvial) location;
                wl.setLocationId(elem.getCodi());
                id = 8;
            }            
            if (id == null){
                logger.info("Location not saved: Error getting LocationGroup");
            } else{
                String jql = "SELECT lg FROM LocationGroup lg WHERE lg.id = " + id;
                Query query = entityManager.createQuery(jql);
                LocationGroup lg = (LocationGroup) query.getSingleResult();
                wl.setLocationGroup(lg);
                listWl.add(wl);
            }
        }

        // If we're editing, limit days and staff to only one
        if (action.equals("edit")) {
            daysElapsed = 1;
            sizeAssigned = 1;
        }


        // Iterate trough assigned Staff List
        for (int i = 0; i < sizeAssigned; i++) {
            Staff staff = (Staff) assignedStaffList.getModel().getElementAt(i);

            // Iterate trough days
            for (int dia = 0; dia < daysElapsed; ++dia) {
                Date newDate = new Date();
                newDate.setTime(initialDate.getTime() + MILIS_DIA * dia);
                Work w;
                if (action.equals("edit")) {
                    w = this.work;
                } else {
                    w = new Work();
                }
                w.setDateWork(newDate);
                w.setStaffId(staff);
                w.setTaskId(task);
                w.setSectionId(section);
                w.setTimeElapsed(timeElapsed);
                w.setComments(comments);
                try {
                    if (action.equals("edit")) {
                        workController.edit(w);
                        logger.info("Work.edit: " + w.getId());
                    } else {
                        workController.create(w);
                        logger.info("Work.create: " + w.getId());
                    }
                } catch (Exception ex) {
                    logger.severe(ex.getMessage());
                }
                if (w.getId() == null) {
                    return;
                }

                // Set Work Locations
                String jql = "SELECT wl FROM WorkLocation wl WHERE wl.workId.id = " + w.getId();
                Query query = entityManager.createQuery(jql);
                List<WorkLocation> list = query.getResultList();
                for (WorkLocation workLocation : list) {
                    try {
                        workLocationController.destroy(workLocation.getId());
                    } catch (NonexistentEntityException ex) {
                        logger.severe(ex.getMessage());
                    }
                }

                for (WorkLocation workLocation : listWl) {
                    workLocation.setWorkId(w);
                    workLocationController.create(workLocation);
                }

            }

            // If service = 'vac' -> Update Calendar of current Staff
            if (task.getSubgroupId().getServiceId().getId().equals("vac")) {
                String title = staff.getNameFull();
                if (daysElapsed < 2) {
                    title = title.substring(0, 12) + "...";
                }
                String title2 = null;
                if (task.getSubgroupId().getId().equals("vac.01")) {
                    title2 = "Vacances";
                } else if (task.getSubgroupId().getId().equals("vac.02")) {
                    title2 = "Baixa";
                } else if (task.getId().equals("vac.03.01")) {
                    title2 = "Sindicat";
                } else if (task.getId().equals("vac.03.02") || task.getId().equals("vac.03.03")) {
                    title2 = "Vacances";
                } else if (task.getSubgroupId().getId().equals("vac.04")) {
                    title2 = "Extra";
                }
                title2 += " (" + totalHours + ")";
                title += " - " + title2;
                String content = task.getDescription();
                Date date2 = new Date();
                date2.setTime(initialDate.getTime() + MILIS_DIA * daysElapsed);
                CalendarManager.createEvent((int) section.getId(), title, content, Utils.dateToString(initialDate), Utils.dateToString(date2));
            }

        }

        // Preserve current values?
        if (action == "new") {
            int res = Utils.askQuestionYesNo(this, bundle.getString("QUESTION_SAVE_WORK"), bundle.getString("QUESTION_SAVE_WORK_TITLE"));
            if (res == 1) {
                resetFields();
            }
            hoursTextField.setText("");
        } else {
            parent.close();
        }

    }


    public void resetFields() {
    	
        reset = true;
        Utils.resetComponentsContainer(this);
        hoursTextField.setText("");
        commentsTextArea.setText("");
        dataIniciDateChooser.setDate(null);
        dataFiDateChooser.setDate(null);
        DefaultListModel model = (DefaultListModel) assignedStaffList.getModel();
        model.clear();
        model = (DefaultListModel) assignedLocationList.getModel();
        model.clear();
        reset = false;
        
    }


    private void changeTask() {
    	
        if (reset) {
            return;
        }
        try {
            Task task = (Task) taskComboBox.getSelectedItem();
            if (task == null) {
                return;
            }
            String serviceId = task.getSubgroupId().getServiceId().getId();
            Section section = task.getSubgroupId().getSectionId();
            if (serviceId.equals("vac")) {
                sectionComboBox.setEnabled(true);
            } else {
                sectionComboBox.setSelectedItem(section);
                sectionComboBox.setEnabled(false);
            }
        } catch (ClassCastException ex) {
            logger.warning(ex.getMessage());
        }
        
    }


    private void changeService() {
    	
        if (workController != null) {
            try {
                Service service = (Service) serviceComboBox.getSelectedItem();
                String sqlTask = bundle.getString("qryTask2");
                if (service != null && service.getId() != "") {
                    sqlTask += " WHERE ser.id = '" + service.getId() + "'";
                }
                sqlTask += " ORDER BY t.description";
                supportTask = GenericController.fillComboBox(sqlTask, taskComboBox, supportTask);
            } catch (ClassCastException ex) {
                logger.warning(ex.getMessage());
            }
        }
        
    }


    private void changeLocationGroup() {
    	
        if (workController != null && locationComboBox != null) {
            try {
                LocationGroup lg = (LocationGroup) locationGroupComboBox.getSelectedItem();
                String sqlLocation = null;
                if (lg != null && lg.getId() != 0) {
                    if (lg.getTableName() != null) {
                        sqlLocation = "SELECT o FROM " + lg.getTableName() + " o ORDER BY o." + lg.getTableId();
                        supportLocation = GenericController.fillComboBox(sqlLocation, locationComboBox, supportLocation);
                    }
                }
            } catch (ClassCastException ex) {
                logger.warning(ex.getMessage());
            }
        }
        
    }


    // <editor-fold defaultstate="collapsed" desc="Auto Generated Code">
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        staffQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryStaff"));
        staffList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : staffQuery.getResultList();
        //taskQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryTask"));
        //taskList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : taskQuery.getResultList();
        serviceQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryService"));
        serviceList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : serviceQuery.getResultList();
        sectionQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qrySection2"));
        sectionList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : sectionQuery.getResultList();
        locationGroupQuery = Beans.isDesignTime() ? null : entityManager.createQuery(bundle.getString("qryLocationGroup"));
        locationGroupList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : locationGroupQuery.getResultList();
        jLabel1 = new javax.swing.JLabel();
        staffComboBox = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        dataIniciDateChooser = new com.toedter.calendar.JDateChooser();
        dataFiDateChooser = new com.toedter.calendar.JDateChooser();
        jLabel5 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        taskComboBox = new javax.swing.JComboBox();
        hoursTextField = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        assignedStaffList = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();
        addStaffButton = new javax.swing.JButton();
        resetButton = new javax.swing.JButton();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        commentsTextArea = new javax.swing.JTextArea();
        serviceComboBox = new javax.swing.JComboBox();
        jLabel9 = new javax.swing.JLabel();
        deleteStaffButton = new javax.swing.JButton();
        locationGroupComboBox = new javax.swing.JComboBox();
        jLabel10 = new javax.swing.JLabel();
        locationComboBox = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        sectionComboBox = new javax.swing.JComboBox();
        jLabel12 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        assignedLocationList = new javax.swing.JList();
        jLabel13 = new javax.swing.JLabel();
        addLocationButton = new javax.swing.JButton();
        deleteLocationButton = new javax.swing.JButton();
        materialBuildingButton = new javax.swing.JButton();

        jLabel1.setText(bundle.getString("TREBALLADOR")); // NOI18N

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, staffList, staffComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        jLabel3.setText(bundle.getString("HORES:")); // NOI18N

        jLabel4.setText(bundle.getString("DATA INICI:")); // NOI18N

        dataIniciDateChooser.setDateFormatString("dd-MM-yyyy");
        dataIniciDateChooser.setFocusTraversalPolicyProvider(true);
        dataIniciDateChooser.setMinSelectableDate(new java.util.Date(978307286000L));

        dataFiDateChooser.setDateFormatString("dd/MM/yyyy");
        dataFiDateChooser.setMaxSelectableDate(new java.util.Date(253370764886000L));
        dataFiDateChooser.setMinSelectableDate(new java.util.Date(978307286000L));

        jLabel5.setText(bundle.getString("DATA FI:")); // NOI18N
        jLabel5.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);

        saveButton.setMnemonic('G');
        saveButton.setText(bundle.getString("SAVE")); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        jLabel6.setText(bundle.getString("TASCA:")); // NOI18N

        taskComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                taskComboBoxActionPerformed(evt);
            }
        });

        hoursTextField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                hoursTextFieldFocusGained(evt);
            }
        });

        jScrollPane1.setViewportView(assignedStaffList);

        jLabel2.setText(bundle.getString("ASSIGNACIÓ:")); // NOI18N

        addStaffButton.setMnemonic('A');
        addStaffButton.setText(bundle.getString("ADD")); // NOI18N
        addStaffButton.setToolTipText("");
        addStaffButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addStaffButtonActionPerformed(evt);
            }
        });

        resetButton.setMnemonic('R');
        resetButton.setText(bundle.getString("RESET")); // NOI18N
        resetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetButtonActionPerformed(evt);
            }
        });

        jLabel8.setText(bundle.getString("COMENTARIS:")); // NOI18N

        jScrollPane3.setName("scroll"); // NOI18N

        commentsTextArea.setColumns(20);
        commentsTextArea.setRows(3);
        commentsTextArea.setName("area"); // NOI18N
        jScrollPane3.setViewportView(commentsTextArea);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, serviceList, serviceComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        serviceComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                serviceComboBoxActionPerformed(evt);
            }
        });

        jLabel9.setText(bundle.getString("SERVEI")); // NOI18N

        deleteStaffButton.setMnemonic('T');
        deleteStaffButton.setText(bundle.getString("REMOVE")); // NOI18N
        deleteStaffButton.setToolTipText("");
        deleteStaffButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteStaffButtonActionPerformed(evt);
            }
        });

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, locationGroupList, locationGroupComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        locationGroupComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                locationGroupComboBoxActionPerformed(evt);
            }
        });

        jLabel10.setText(bundle.getString("AMBIT:")); // NOI18N

        jLabel11.setText(bundle.getString("LOCALITZACIÓ:")); // NOI18N

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, sectionList, sectionComboBox);
        bindingGroup.addBinding(jComboBoxBinding);

        jLabel12.setText(bundle.getString("SECTION:")); // NOI18N

        jScrollPane2.setViewportView(assignedLocationList);

        jLabel13.setText(bundle.getString("ASSIGNACIÓ:")); // NOI18N

        addLocationButton.setMnemonic('A');
        addLocationButton.setText(bundle.getString("ADD")); // NOI18N
        addLocationButton.setToolTipText("");
        addLocationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addLocationButtonActionPerformed(evt);
            }
        });

        deleteLocationButton.setMnemonic('T');
        deleteLocationButton.setText(bundle.getString("REMOVE")); // NOI18N
        deleteLocationButton.setToolTipText("");
        deleteLocationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteLocationButtonActionPerformed(evt);
            }
        });

        materialBuildingButton.setMnemonic('E');
        materialBuildingButton.setText(bundle.getString("MATERIALS")); // NOI18N
        materialBuildingButton.setToolTipText("");
        materialBuildingButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                materialBuildingButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(20, 20, 20)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel5))
                                .addGap(37, 37, 37)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(dataFiDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(dataIniciDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(staffComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(addStaffButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(deleteStaffButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(jLabel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jLabel3))
                                    .addComponent(jLabel12, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel11)
                                    .addComponent(jLabel10)
                                    .addComponent(jLabel9, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addGap(0, 0, Short.MAX_VALUE)
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                            .addComponent(locationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addComponent(hoursTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 57, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(taskComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(serviceComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(locationGroupComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addComponent(sectionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE))
                                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                            .addGroup(layout.createSequentialGroup()
                                                .addGap(18, 18, 18)
                                                .addComponent(deleteLocationButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(layout.createSequentialGroup()
                                                .addGap(18, 18, 18)
                                                .addComponent(materialBuildingButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
                                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(addLocationButton, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(0, 0, Short.MAX_VALUE))))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(185, 185, 185)
                        .addComponent(saveButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(resetButton, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dataIniciDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(dataFiDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(staffComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1)
                    .addComponent(addStaffButton))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(deleteStaffButton)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(jLabel2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(serviceComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel9)
                    .addComponent(materialBuildingButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(taskComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(sectionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel12))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(hoursTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(locationGroupComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel10))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(locationComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel11)
                    .addComponent(addLocationButton))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addComponent(jLabel13))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(deleteLocationButton)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel8, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(resetButton))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents


    public static void main(String[] args) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MaterialPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MaterialPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MaterialPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MaterialPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.setContentPane(new WorkAddPanel());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setVisible(true);
            }
        });
    }
    // </editor-fold>

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        try {
            saveWork();
        } catch (RuntimeException e) {
            logger.warning(e.getMessage());
            JOptionPane.showMessageDialog(this, bundle.getString("ERROR_DB_SAVE") + "\n" + bundle.getString("SEE_LOG"),
                bundle.getString("ERROR_VALIDATE"), JOptionPane.WARNING_MESSAGE);
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void addStaffButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addStaffButtonActionPerformed
        addStaffToList();
    }//GEN-LAST:event_addStaffButtonActionPerformed

    private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
        resetFields();
    }//GEN-LAST:event_resetButtonActionPerformed

    private void serviceComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_serviceComboBoxActionPerformed
        changeService();
    }//GEN-LAST:event_serviceComboBoxActionPerformed

    private void deleteStaffButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteStaffButtonActionPerformed
        removeStaffToList();
    }//GEN-LAST:event_deleteStaffButtonActionPerformed

    private void taskComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_taskComboBoxActionPerformed
        changeTask();
    }//GEN-LAST:event_taskComboBoxActionPerformed

    private void addLocationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addLocationButtonActionPerformed
        addLocationToList();
    }//GEN-LAST:event_addLocationButtonActionPerformed

    private void deleteLocationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteLocationButtonActionPerformed
        removeLocationToList();
    }//GEN-LAST:event_deleteLocationButtonActionPerformed

    private void locationGroupComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_locationGroupComboBoxActionPerformed
        changeLocationGroup();
    }//GEN-LAST:event_locationGroupComboBoxActionPerformed

    private void materialBuildingButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_materialBuildingButtonActionPerformed
        MainClass.mdi.manageFrames(MainClass.mdi.materialBuildingFrame);
    }//GEN-LAST:event_materialBuildingButtonActionPerformed

    private void hoursTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_hoursTextFieldFocusGained
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                hoursTextField.selectAll();
            }
        });
    }//GEN-LAST:event_hoursTextFieldFocusGained
    // <editor-fold defaultstate="collapsed" desc="Variables declaration">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addLocationButton;
    private javax.swing.JButton addStaffButton;
    private javax.swing.JList assignedLocationList;
    private javax.swing.JList assignedStaffList;
    private javax.swing.JTextArea commentsTextArea;
    private com.toedter.calendar.JDateChooser dataFiDateChooser;
    private com.toedter.calendar.JDateChooser dataIniciDateChooser;
    private javax.swing.JButton deleteLocationButton;
    private javax.swing.JButton deleteStaffButton;
    private javax.swing.JFormattedTextField hoursTextField;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JComboBox locationComboBox;
    private javax.swing.JComboBox locationGroupComboBox;
    private java.util.List<org.gesplan.entity.Service> locationGroupList;
    private javax.persistence.Query locationGroupQuery;
    private javax.swing.JButton materialBuildingButton;
    private javax.swing.JButton resetButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox sectionComboBox;
    private java.util.List<org.gesplan.entity.Service> sectionList;
    private javax.persistence.Query sectionQuery;
    private javax.swing.JComboBox serviceComboBox;
    private java.util.List<org.gesplan.entity.Service> serviceList;
    private javax.persistence.Query serviceQuery;
    private javax.swing.JComboBox staffComboBox;
    private java.util.List staffList;
    private javax.persistence.Query staffQuery;
    private javax.swing.JComboBox taskComboBox;
    //private java.util.List taskList;
    //private javax.persistence.Query taskQuery;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables
    // </editor-fold>
}